new Vue({
    el: '#permissions',
    data: function () {
        return {
            searchForm: { //查询条件
                searchDate: new Date(),
                branch: "",
                cso: ""
            },
            myChart: '',
            branchs: [],//分公司
            CSOs: [],
            orgnsTree: {},
            activeName: 'yearOnYear',
            APENBP: true, //APE--false;折算NBP--true
           //目标达成
            xAxisGoalAttainment: {
                axisLabel: {
                    rotate: 35,
                    interval: 0
                },
                data: []
            }, 
            legendDataGoalAttainment: [], 
            seriesGoalAttainment: [],
          //同比增长
            xAxisYearOnYear: {
                axisLabel: {
                    rotate: 35,
                    interval: 0
                },
                data: []
            }, 
            legendDataYearOnYear: [], 
            seriesYearOnYear: [],
          //机构占比
            legendDataInstitutionsOf: [],  
            seriesInstitutionsOf: [{
                name: 2018,
                type: 'pie',
                center: ['40%', '50%'],
                radius: [120, 180],
                data: []
            }],
          //趋势分析
            xAxisTrendAlalysis: {data: []}, 
            seriesTrendAlalysis: [{
                type: 'bar',
                label: {
                    normal: {
                        show: true,
                        position: ['40%', -20],
                        color: '#e6061f'
                    }
                },
                data: [],
                barWidth: '40%'
            }],
          //机构排名
            xAxisInstitutionRanking: {data: []}, 
            seriesInstitutionRanking: [{
                type: 'bar',
                label: {
                    normal: {
                        show: true,
                        position: ['30%', -20],
                        color: '#e6061f'
                    }
                },
                data: [],
                barWidth: '40%'
            }],
        }
    },
    mounted: function () {
    	this.getGlobalConstraints()
        this.resizeChart()
        this.query()
        //this.initChartBar('目标达成', this.xAxisGoalAttainment, this.legendDataGoalAttainment, this.seriesGoalAttainment)
    },
    methods: {
    	//获取数据字典数据
        getGlobalConstraints:function(){
            var _this = this;
            $.ajax({
                url: '/getGlobalConstraints',
                type: 'get',
                dataType: 'json',
                async: false,//同步
                success: function (res) {
                	_this.orgnsTree = res.data.orgnsTree
                    _this.branchs = _this.orgnsTree.orgnsChild
                },
                error: function (err) {
                	if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
                    errorMessage(_this.$message, '查询人数据字典出错！错误代码：'+(err.status))
                }
            })
        },
        //清空
    	resetSearchForm: function (formName) {
      		this.$refs[formName].resetFields()
      	},
      	query: function(){
      		var _this = this;
        	if(_this.searchForm.searchDate==null){
        		_this.searchForm.searchDate = new Date()
        	}
        	if (this.myChart && this.myChart.dispose) {
        		this.myChart.showLoading()
        	}
        	$.ajax({
	             url: '/objectif/findData',
	             data:{"data":JSON.stringify(_this.searchForm),"ape_nbp":this.APENBP?'NBP':'APE'},
	             type: 'post',
	             async: true,
	             dataType: 'json',
	             success: function (res) {
	            	//目标达成
	            	_this.xAxisGoalAttainment.data = res.data.xAxisGoalAttainmentData
	            	_this.legendDataGoalAttainment = res.data.legendDataGoalAttainment
	            	_this.seriesGoalAttainment = res.data.seriesGoalAttainmentList
	            	
	            	//同比增长
	            	_this.xAxisYearOnYear.data = res.data.xAxisYearOnYearData;
	            	_this.legendDataYearOnYear = res.data.legendDataYearOnYear;
	            	_this.seriesYearOnYear = res.data.seriesYearOnYearList;
	            	
	            	//机构占比
	            	_this.legendDataInstitutionsOf = res.data.legendDataInstitutionsOf
	            	_this.seriesInstitutionsOf[0].data = res.data.seriesInstitutionsOfList
	            	
	            	//趋势分析
	            	_this.xAxisTrendAlalysis.data = res.data.xAxisTrendAlalysisData
	            	_this.seriesTrendAlalysis[0].data = res.data.seriesTrendAlalysisData
	            	
	                //机构排名
	                _this.xAxisInstitutionRanking.data = res.data.xAxisInstitutionRankingData
	                _this.seriesInstitutionRanking[0].data = res.data.seriesInstitutionRanking
	                _this.draw(_this.activeName)
	             },
	             error: function (err) {
	                 if(err.responseJSON.message=="session clean"){
	                     errorMessage(_this.$message, '登陆已失效重新登陆!');
	                     toLogin();
	                     return;
	                 }
	                 if(err.status == 403){
	                     errorMessage(_this.$message, "没有权限，请先申请该权限！");
	                     return;
	                 }
	                 errorMessage(_this.$message,err);
	             }
        	})
        	//刷新选择的tab
        	console.info("当前tab:"+this.activeName)
        	
      	},
      	 /**
         * 改变分公司
         * @param value
         */
    	changeBranch: function (value) {
    		this.searchForm.cso = ""
            console.info("searchForm.branch:",this.searchForm.cso)
            if(this.searchForm.cso){
                this.searchForm.cso = "";
            }
            var $currentBranch = this.orgnsTree.orgnsChild.filter(function (val) {
            	console.info("1:"+(val.value === value));
                return (val.value === value);
            })
            if($currentBranch[0].orgnsChild !== null) {
                // this.CSOs = [{"label":"","orgnsChild":"","value":""}]
                this.CSOs = ($currentBranch[0].orgnsChild)
                if($currentBranch[0].orgnsChild.length == 0 ){
                    this.CSOs.push($currentBranch[0])
                }
                //如果当前选择的是2002（广东省分公司），cso部分不显示广东省分公司南区、广东省分公司北区，
                // 直接把广东省分公司南区、广东省分公司北区的下级机构放到CSO数组中显示出来
                if(value=="2002"){
                    this.CSOs = this.getGuangDongShengNorthSouthChildOrgns(this.CSOs);
                }
                //根据json对象中的value的值去除数组中重复的数据
                this.CSOs = this.uniqueArray(this.CSOs,"value")
                this.branchs = this.uniqueArray(this.branchs,"value")
                this.CSOs.push({})
            } else {
                this.CSOs = []
                Vue.set(this.CSOs,0,$currentBranch[0])
            }
        },
        /**
         * 把广东省分公司南区、广东省分公司北区的下级机构放到CSO数组中
         */
        getGuangDongShengNorthSouthChildOrgns:function(csoArr){
            var csoArrNew = [];
            csoArr.forEach(function (item) {
                //广东省分公司南区、广东省分公司北区的不在cso中显示，只显示他俩的下级机构
                if(item.value== "B103050" || item.value== "B103051"){
                    csoArrNew = csoArrNew.concat(item.orgnsChild);
                }else{
                    csoArrNew.push(item)
                }
            })
            return csoArrNew;
        },
        //切换APE和折算NBP
        switchApeNbp: function () {
        	console.info("APE--false;折算NBP--true:"+this.APENBP);
        	//调用查询获取切换数据
        	this.query();
        },
       //tab切换
        handleClick: function (tab, event) { 
        	this.draw(tab.name)
        },
        resizeChart: function () { //计算eChart画布尺寸
            this.$refs['myChart'].style.width = document.querySelector('.card-body').offsetWidth - 230 + 'px'
            this.$refs['myChart'].style.height = 600 + 'px'
            console.log(this.$refs['myChart'].style.width)
        },
        initChartBar: function (title, xAxis, legendData, series) { //柱状图
            var _this = this
            this.myChart = echarts.init(this.$refs['myChart'])
            this.myChart.showLoading()
            var option = {
                title: {
                    text: title,
                    left: 'center',
                    textStyle: {
                        fontSize: 22
                    }
                },
                color: ['#d2001f', '#2a4556', '#4fa3ab'], //调色盘
                // color: ['#e6061f', '#fa9200', '#eff900'], //调色盘
                legend: {
                    data: legendData, //图例项名称
                    orient: 'horizontal', //图例列表的布局朝向
                    right: 60
                },
                tooltip: { //提示框组件
                    show: true,
                    trigger: 'axis'
                },
                toolbox: {
                    show: true,
                    right: 20,
                    feature: {
                        saveAsImage: { //保存图片
                            type: 'png',
                            name: title,
                            title: '保存为图片',
                            show: true
                        }
                    }
                },
                grid: {
                    // left: 50, //离容器左侧距离
                    // right: 5
                    left: 100, //离容器左侧距离
                    right: 30,
                    bottom: 100
                },
                xAxis: xAxis,
                yAxis: {},
                dataZoom: [{
                    type: 'slider',
                    show: true,
                    xAxisIndex: [0],
                    start: 0,
                    end: 100,
                    bottom:0
                }],
                series: series
            }
            this.myChart.clear()
            this.myChart.setOption(option)
            window.onresize = function () {
                _this.resizeChart()
                _this.myChart.resize()
            }
        },
        initChartPie: function (title, legendData, series) { //饼图
            var _this = this
            this.myChart = echarts.init(this.$refs['myChart'])
            var option = {
                title: {
                    text: title,
                    left: 'center',
                    textStyle: {
                        fontSize: 22
                    }
                },
                color: ['#ef8f30', '#fbd043', '#f6aa39', '#dc6041', '#f49e4a', '#f8c455', '#eb7c2b'], //调色盘
                legend: {
                    data: legendData, //图例项名称
                    orient: 'vertical', //图例列表的布局朝向
                    right: 60
                },
                tooltip: { //提示框组件
                    show: true,
                    trigger: 'item'
                },
                toolbox: {
                    show: true,
                    right: 20,
                    feature: {
                        saveAsImage: { //保存图片
                            type: 'png',
                            name: title,
                            title: '保存为图片',
                            show: true
                        }
                    }
                },
                series: series
            }
            this.myChart.clear()
            this.myChart.setOption(option)
            window.onresize = function () {
                _this.resizeChart()
                _this.myChart.resize()
            }
        },
        /**
         * JSON数组去重
         * @param: [array] json Array
         * @param: [string] 唯一的key名，根据此键名进行去重
         */
        uniqueArray:function(array, key){

            var result = [array[0]];
            for(var i = 1; i < array.length; i++){
                var item = array[i];
                var repeat = false;
                for (var j = 0; j < result.length; j++) {
                    if (item[key] == result[j][key]) {
                        repeat = true;
                        break;
                    }
                }
                if (!repeat) {
                    result.push(item);
                }
            }
            return result;
        },
        //绘制显示图案
        draw: function(tabname){
        	switch(tabname) {
           /* case 'goalAttainment': 
                this.initChartBar('目标达成', this.xAxisGoalAttainment, this.legendDataGoalAttainment, this.seriesGoalAttainment)
                this.myChart.hideLoading()
                break;*/
            case 'yearOnYear': 
                this.initChartBar('同比增长', this.xAxisYearOnYear, this.legendDataYearOnYear, this.seriesYearOnYear)
                this.myChart.hideLoading()
                break;
            case 'institutionsOf': 
                this.initChartPie('机构占比', this.legendDataInstitutionsOf, this.seriesInstitutionsOf)
                this.myChart.hideLoading()
                break;
            case 'trendAlalysis': 
                this.initChartBar('趋势分析', this.xAxisTrendAlalysis, '', this.seriesTrendAlalysis)
                this.myChart.hideLoading()
                break;
            case 'institutionRanking': 
                this.initChartBar('机构排名', this.xAxisInstitutionRanking, '', this.seriesInstitutionRanking)
                this.myChart.hideLoading()
                break;
        }
        }
    }
})
